<?php
/*********************************************************************************
 * Copyright (C) 2011-2013 X2Engine Inc. All Rights Reserved.
 *
 * X2Engine Inc.
 * P.O. Box 66752
 * Scotts Valley, California 95067 USA
 *
 * Company website: http://www.x2engine.com
 * Community and support website: http://www.x2community.com
 *
 * X2Engine Inc. grants you a perpetual, non-exclusive, non-transferable license
 * to install and use this Software for your internal business purposes.
 * You shall not modify, distribute, license or sublicense the Software.
 * Title, ownership, and all intellectual property rights in the Software belong
 * exclusively to X2Engine.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT.
 ********************************************************************************/

/* @edition:pro */

Yii::app()->clientScript->packages = $this->module->packages;
Yii::app()->clientScript->registerPackage('jqplot');
Yii::app()->clientScript->registerScriptFile(Yii::app()->getBaseUrl().'/js/emailEditor.js');
Yii::app()->clientScript->registerScriptFile(Yii::app()->getBaseUrl().'/js/inlineEmailForm.js');
Yii::app()->clientScript->registerCssFile($this->module->assetsUrl . '/css/printReport.css');
?>
<?php
$this->actionMenu = $this->formatMenu(array(
	array('label' => Yii::t('charts', 'Grid Builder')),
	array('label' => Yii::t('charts', 'Lead Performance'), 'url' => array('leadPerformance')),
	array('label' => Yii::t('charts', 'Saved Reports'),'url'=>array('savedReports')),
	array('label' => Yii::t('charts', 'Deal Report'),'url'=>array('dealReport')),
	array('label' => Yii::t('app', 'Workflow'),'url'=>array('workflow')),
    array('label' => Yii::t('charts', 'User Activity'),'url'=>array('activityReport')),
    array('label' => Yii::t('services', 'Case Report'),'url'=>array('/services/servicesReport')),
));
Yii::app()->clientScript->registerScript('leadPerformance', "
	$('#startDate,#endDate').change(function() {
		$('#dateRange').val('custom');
	});

	$('#lead-volume-chart').bind('jqplotDataHighlight', function (e, seriesIndex, pointIndex, data) {
			$('#pie-tooltip').html('<div style=\"font-size:14px;font-weight:bold;padding:5px;color:#000;background:white;background:rgba(255,255,255);\">' + data[0] + '</span>');
			$('#pie-tooltip').show();

			var chart_left = $('#lead-volume-chart').position().left;
				var chart_top = $('#lead-volume-chart').position().top;

			$(document).bind('mousemove.pieChart',function(e) {
				x = e.pageX; //plot.axes.xaxis.u2p(data[0]),  // convert x axis unita to pixels
				y = e.pageY; //plot.axes.yaxis.u2p(data[1]);  // convert y axis units to pixels
				$('#pie-tooltip').css({left:x-chart_left+5, top:y-50});
			});
		});
$zero
		// Bind a function to the unhighlight event to clean up after highlighting.
		$('#lead-volume-chart').bind('jqplotDataUnhighlight',
		function (e, seriesIndex, pointIndex, data) {
			$(document).unbind('mousemove.pieChart');
			$('#pie-tooltip').empty();
			$('#pie-tooltip').hide();
		});

", CClientScript::POS_READY);
?>
<div class="page-title"><h2><?php echo Yii::t('charts', 'Grid Builder'); ?></h2></div>
<div class="form">

    <?php $_GET = array();

   $form = $this->beginWidget('CActiveForm', array(
        'action' => 'gridReport',
        'id' => 'selectModuleForm',
        'enableAjaxValidation' => false,
        'method' => 'get'
            ));
	?>

    <div class="row">
    	<div class="cell">
    		<label><?php echo Yii::t('app','Module');?></label>
				<?php echo CHtml::dropDownList('module', $module, array('Accounts' => Yii::t('app','Accounts'), 'Contacts'=>Yii::t('app','Contacts'), 'Services'=>Yii::t('app','Cases'), 'Opportunity' => Yii::t('app','Opportunities')), array('id'=>'select-module-dropdown')); ?>
    	</div>
    </div>

   <?php
	Yii::app()->clientScript->registerScript('leadPerformance', "
		$(function() {
			$('#select-module-dropdown').change(function() {
				$('#selectModuleForm').submit();
			});
		});
	");

   $this->endWidget();

   $form = $this->beginWidget('CActiveForm', array(
        'action' => 'gridReport',
        'id' => 'dateRangeForm',
        'enableAjaxValidation' => false,
        'method' => 'get'
            ));

    // $range = 30; //$model->dateRange;
    // echo $startDate .' '.$endDate;
    $userName = Yii::app()->user->getName();
    $filters = array(
        'createDate BETWEEN ' . $dateRange['start'] . ' AND ' . $dateRange['end']
    );
    ?>

    <input type="hidden" name="module" value="<?php echo $module; ?>"> <?php // remember the selected module ?>

    <div class="row">

        <div class="cell">
            <?php echo CHtml::label(Yii::t('charts', 'Start Date'), 'startDate'); ?>
            <?php
            Yii::import('application.extensions.CJuiDateTimePicker.CJuiDateTimePicker');

            $this->widget('CJuiDateTimePicker', array(
                'name' => 'start',
                // 'value'=>$startDate,
                'value' => Formatter::formatDate($dateRange['start']),
                // 'title'=>Yii::t('app','Start Date'),
                // 'model'=>$model, //Model object
                // 'attribute'=>$field->fieldName, //attribute name
                'mode' => 'date', //use "time","date" or "datetime" (default)
                'options' => array(
                    'dateFormat' => Formatter::formatDatePicker(),
                    'changeMonth' => true,
                    'changeYear' => true,
                ), // jquery plugin options
                'htmlOptions' => array('id' => 'startDate', 'width' => 20),
                'language' => (Yii::app()->language == 'en') ? '' : Yii::app()->getLanguage(),
            ));
            ?>
        </div>
        <div class="cell">
<?php echo CHtml::label(Yii::t('charts', 'End Date'), 'startDate'); ?>
            <?php
            $this->widget('CJuiDateTimePicker', array(
                'name' => 'end',
                'value' => Formatter::formatDate($dateRange['end']),
                // 'value'=>$endDate,|| (isset($_GET['cellType']) && $_GET['cellType'] == 'frequency')
                'mode' => 'date', //use "time","date" or "datetime" (default)
                'options' => array(
                    'dateFormat' => Formatter::formatDatePicker(),
                    'changeMonth' => true,
                    'changeYear' => true,
                ),
                'htmlOptions' => array('id' => 'endDate', 'width' => 20),
                'language' => (Yii::app()->language == 'en') ? '' : Yii::app()->getLanguage(),
            ));
            ?>
        </div>
        <div class="cell">
<?php echo CHtml::label(Yii::t('charts', 'Date Range'), 'range'); ?>
            <?php
            echo CHtml::dropDownList('range', $dateRange['range'], array(
                'custom' => Yii::t('charts', 'Custom'),
                'thisWeek' => Yii::t('charts', 'This Week'),
                'thisMonth' => Yii::t('charts', 'This Month'),
                'lastWeek' => Yii::t('charts', 'Last Week'),
                'lastMonth' => Yii::t('charts', 'Last Month'),
                // 'lastQuarter'=>Yii::t('charts','Last Quarter'),
                'thisYear' => Yii::t('charts', 'This Year'),
                'lastYear' => Yii::t('charts', 'Last Year'),
                'all' => Yii::t('charts', 'All Time'),
                    ), array('id' => 'dateRange'));
            ?>
        </div>

    </div>

    <div class="row">
        <div class="cell">
            <label><?php echo Yii::t('charts','Row Field');?></label>
<?php
$temp = array();
$tempFields = "'";
$fields = Fields::model()->findAllByAttributes(array('modelName' => $module));
foreach ($fields as $field) {
    $temp[$field->fieldName] = X2Model::model(ucfirst($module))->getAttributeLabel($field->fieldName);
    $tempFields.='<option value="' . $field->fieldName . '">'
            . Yii::t($module=='Opportunity'?"opportunities":strtolower($module), $field->attributeLabel)
            . '</option>';
}
$tempFields.="'";
echo CHtml::dropDownList('field1', empty($field1) ? 'assignedTo' : $field1, $temp);
?>
        </div>
        <div class="cell">
            <label><?php echo Yii::t('charts','Column Field');?></label>
<?php echo CHtml::dropDownList('field2', empty($field2) ? 'leadSource' : $field2, $temp); ?>
        </div>
        <div class="cell">
            <label><?php echo Yii::t('charts','Hide empty rows/columns?');?></label>

<?php echo CHtml::checkBox('zero', $zero); ?>
        </div>

    </div>
    <div class="row">
        <div class="cell">
            <label><?php echo Yii::t('charts','Cell Data Type');?></label>
<?php
echo CHtml::dropDownList('cellType', empty($cellType) ? "" : $cellType, array('' => Yii::t('charts',"Count"), 'sum' => Yii::t('charts',"Sum"), 'avg' => Yii::t('charts','Average')), array('onchange' => 'toggleCellData()', 'id' => 'cell-type'));
?>
        </div>
        <div class="cell" id="cell-data" style="<?php echo empty($cellType) ? "display:none" : ""; ?>">
            <label><?php echo Yii::t('charts','Cell Data Field');?></label>
            <?php
            $tempInts = "'";
            $tempIntsArr = array();
            $fields = Fields::model()->findAll("modelName='$module' AND (type='int' OR type='currency')");
            foreach ($fields as $field) {
                $tempIntsArr[$field->fieldName] = $field->attributeLabel;
                $tempInts.='<option value="' . $field->fieldName . '">'
                        . $field->attributeLabel
                        . '</option>';
            }
            $tempInts.="'";
            ?>
            <?php echo CHtml::dropDownList('cellData', empty($cellData) ? "" : $cellData, empty($cellType) ? array() : ($cellType == 'frequency' ? $temp : $tempIntsArr), array('id' => 'cell-data-dropdown', 'style' => empty($cellType) ? 'display:none' : '')); ?>
        </div>


        <div class="cell">
            <?php echo CHtml::submitButton(Yii::t('charts', 'Go'), array('class' => 'x2-button btn btn-mini  btn-yellow', 'style' => 'margin-top:13px;')); ?>
        </div>
    </div>
<?php
$pie = '<a class=\"x2-pie-chart-button\" onclick=\"return false;\" href=\"#\">['.Yii::t('charts','pie').']</span>';
$columns = array(
    'user' => array(
        'name' => $field1,
        'header' =>  X2Model::model($module)->getAttributeLabel($field1),
        'value' => '(empty($data["id"])? $data["name"] : $data["name"]) . \' <a class="x2-pie-chart-button" onclick="rowPieChart(\'.$row.\'); return false;" href="#">['.Yii::t('charts','pie').']</span> <a class="x2-bar-graph-button" onclick="rowBarGraph(\'.$row.\'); return false;" href="#">['.Yii::t('charts','bar').']</span>\'',
        'type' => 'raw',
        'headerHtmlOptions' => array('style' => 'width:20%')
    ),
    'leads' => array(
        'name' => 'leads',
        'header' => Yii::t('charts', "Total Records") . ' <a class="x2-pie-chart-button" onclick="columnPieChart(0); return false;" href="#">['.Yii::t('charts','pie').']</a> <a class="x2-bar-graph-button" onclick="columnBarGraph(0); return false;" href="#">['.Yii::t('charts','bar').']</a>',
        'value' => '$data["leads"]',
        'type' => 'raw',
    ),
);
if (count($columnData) > 0) {
	$i = 1;
    foreach ($columnData as $name) {
        $trans="contacts";
        if($name=='(none)')
            $trans="charts";
        $columns[$name] = array(
            'name' => $name,
            'header' => Yii::t($trans, $name) . ' <a class="x2-pie-chart-button" onclick="columnPieChart('.$i.'); return false;" href="#">['.Yii::t('charts','pie').']</a> <a class="x2-bar-graph-button" onclick="columnBarGraph('.$i.'); return false;" href="#">['.Yii::t('charts','bar').']</a>',
            'value' => '$data["' . $name . '"]',
            'type' => 'raw',
        );
        $i++;
    }
}

if (isset($dataProvider)) {
    $this->widget('zii.widgets.grid.CGridView', array(
        'id' => 'lead-activity-grid',
        'baseScriptUrl' => Yii::app()->request->baseUrl . '/themes/' . Yii::app()->theme->name . '/css/gridview',
        'template' => '{items}{pager}',
        // 'template'=> '<h2>'.Yii::t('charts','Lead Activity').'</h2><div class="title-bar">'
        // .CHtml::link(Yii::t('app','Advanced Search'),'#',array('class'=>'search-button')) . ' | '
        // .CHtml::link(Yii::t('app','Clear Filters'),array(Yii::app()->controller->action->id,'clearFilters'=>1)) . ' | '
        // .CHtml::link(Yii::t('app','Columns'),'javascript:void(0);',array('class'=>'column-selector-link'))
        // .'{summary}</div>{items}{pager}',
        'dataProvider' => $dataProvider,
        // 'enableSorting'=>false,
        'enablePagination' => false,
        'ajaxUpdate'=>false,
        // 'model'=>$model,
        //'filter'=>$model,
        // 'columns'=>$columns,
        //'modelName'=>'Contacts',
        // 'viewName'=>'leadpercontacts',
        'columns' => $columns,
    ));
?>
<?php $column_names = array_keys($columns); ?>
<script class="code" type="text/javascript">
$(document).ready(function(){
	$('body').data('printReportUrl', '<?php echo $this->createUrl('printReport'); ?>');
	$('body').data('saveTempImageUrl', '<?php echo $this->createUrl('saveTempImage'); ?>');
	$('body').data('removeTempFileUrl', '<?php echo Yii::app()->createUrl('site/removeTmpUpload'); ?>');
$.jqplot.config.enablePlugins = true;
	row_names = [];
		<?php foreach($dataProvider->data as $row) { ?>
			<?php echo "row_names.push ('{$row['name']}');"; ?>
		<?php } ?>

	column_names = [];
		<?php foreach($column_names as $column_name) { ?>
			<?php if($column_name == 'user') { ?>
				<?php echo "column_names.push ('" . Yii::t('charts', "Total Records") . "');"; ?>
			<?php } else if($column_name != 'leads') { ?>
				<?php echo "column_names.push ('$column_name');"; ?>
			<?php } ?>
		<?php } ?>

	report_data = [];
	<?php foreach($dataProvider->data as $row) { ?>
		report_data.push ([]);
		<?php foreach($row as $key=>$column) { ?>
		<?php if(in_array($key, $column_names) && $key != "leads") { ?>
				<?php echo "report_data[report_data.length - 1].push (['$key', $column]);"; ?>
			<?php } ?>
		<?php } ?>
	<?php } ?>

	report_column_data = [];
	<?php foreach($dataProvider->data as $row) { ?>
        report_column_data.push ([]);
		<?php foreach($row as $key=>$column) { ?>
		<?php if(in_array($key, $column_names)) { ?>
				<?php echo "report_column_data[report_column_data.length - 1].".
                    "push (['$key', $column]);"; ?>
			<?php } ?>
		<?php } ?>
	<?php } ?>

	// move Total Records to beginning of columns
	for(var i=0; i<report_column_data.length - 1; i++) {
		var temp = report_column_data[i].pop();
		report_column_data[i].unshift(temp);
	}

	<?php if($report) { ?>
		<?php $charts = json_decode($report->rowPie); ?>
        	<?php for($i=0; $i<sizeof($charts); $i+=2) { ?>
        		<?php if($charts[$i+1] == "rowpie") { ?>
        			rowPieChart(<?php echo $charts[$i]; ?>);
        		<?php } else if($charts[$i+1] == "rowbar") { ?>
        			rowBarGraph(<?php echo $charts[$i]; ?>);
        		<?php } else if($charts[$i+1] == "columnpie") { ?>
        			columnPieChart(<?php echo $charts[$i]; ?>);
        		<?php } else if($charts[$i+1] == "columnbar") { ?>
        			columnBarGraph(<?php echo $charts[$i]; ?>);
        		<?php } ?>
        	<?php } ?>
	<?php } ?>

});
</script>
<?php


}
?><br>
    <?php
    if (isset($exportFlag) && $exportFlag){
        echo CHtml::link(Yii::t('charts','Export to CSV'), (@$_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . Yii::app()->request->baseUrl . '/gridExport.csv', array('class' => 'x2-button btn btn-mini  btn-yellow'));
        echo CHtml::link(Yii::t('charts','Save Report'), array('saveReport','type'=>'grid','field1'=>$field1,'field2'=>$field2,'zero'=>$zero,'start'=>$dateRange['start'],'end'=>$dateRange['end'],'range'=>$dateRange['range'],'cellType'=>$cellType,'cellData'=>$cellData), array('class' => 'x2-button btn btn-mini  btn-yellow', 'id'=>'save-report-button', 'onClick'=>'beforeSaveReport();'));
        echo CHtml::link(Yii::t('charts','Print Report'), '#', array('id'=>'print-report-button', 'class' => 'x2-button btn btn-mini  btn-yellow', 'onClick'=>'printReport();'));
        echo CHtml::link(Yii::t('charts','Email Report'), '#', array('id'=>'email-report-button', 'class' => 'x2-button btn btn-mini  btn-yellow', 'onClick'=>'emailReport();'));
    }
    ?>
    <?php
    $form = $this->endWidget();
    ?>

</div>

<script>

    function toggleCellData(){
        var type=$('#cell-type').val();
        if(type==''){
            $('#cell-data').hide();
        }else if(type=='frequency'){
            $('#cell-data').show();
            $('#cell-data-dropdown').show();
            $('#cell-data-dropdown').html(<?php echo $tempFields; ?>)
        }else{
            $('#cell-data').show();
            $('#cell-data-dropdown').show();
            $('#cell-data-dropdown').html(<?php echo $tempInts; ?>)
        }
    }
</script>
<div id="publisher-form">
</div>

<?php
$this->widget('InlineEmailForm',
	array(
		'attributes'=>array(
			'to'=>'',
			// 'subject'=>'hi',
			// 'redirect'=>'contacts/'.$model->id,
			'modelName'=>'Reports',
			'modelId'=>$model->id,
		),
		'startHidden'=>true,
	)
);
?>

<div id="x2-report-charts" style="margin: 0 auto; width: 500px;">
</div>
